/*
 * Created by: Peter Weissbrod
 * Created: Tuesday, January 22, 2008
 */
using System;
using PostSharp.Laos;
using PostSharp.UserSamples.Exceptions;
using PostSharp.UserSamples.Utils;

namespace PostSharp.UserSamples.Validators
{
    /// <summary>
    /// Throws ValidationException if the setter argument is out of the defined range
    /// </summary>
    [Serializable]
    public class FloatRangeValidator : OnMethodBoundaryAspect
    {
        /// <summary>
        /// ceiling of the defined range
        /// </summary>
        public float MaxVal
        {
            get;
            set;
        }
        /// <summary>
        /// floor of the defined range
        /// </summary>
        public float MinVal
        {
            get;
            set;
        }
        /// <summary>
        /// restrict to public property setters of type float
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public override bool CompileTimeValidate(System.Reflection.MethodBase method)
        {
            return CompileTimeValidateScenario.ValidateForPublicPropertySetter(method) &&
                   CompileTimeValidateScenario.RestrictPropertySetterToSpecificType(method, typeof (float));
        }
        /// <summary>
        /// validate before property is set
        /// </summary>
        /// <param name="eventArgs"></param>
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            if (eventArgs.GetArguments() != null)
            {
                float value = (float) eventArgs.GetArguments()[0];
                if (value.CompareTo(MinVal) < 0)
                    throw new ValidationException("Scalar value [" + value + "] was below minimum [" + MinVal + "]",
                                                  eventArgs);
                if (value.CompareTo(MaxVal) > 0)
                    throw new ValidationException("Scalar value [" + value + "] was above maximum [" + MinVal + "]",
                                                  eventArgs);
            }
            base.OnEntry(eventArgs);
        }
    }
}